package com.thinkgem.jeesite.modules.bookstore;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.book.dao.BookPurchaseDao;
import com.thinkgem.jeesite.modules.book.entity.*;
import com.thinkgem.jeesite.modules.book.service.BookMgrService;
import com.thinkgem.jeesite.modules.book.service.BookPurchaseService;
import com.thinkgem.jeesite.modules.book.service.BookStoreService;
import com.thinkgem.jeesite.modules.bookset.entity.BkPlace;
import com.thinkgem.jeesite.modules.bookset.service.BookPlaceService;
import com.thinkgem.jeesite.modules.shelf.entity.BkShelf;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程个人任务相关Controller
 *
 * @author ThinkGem
 * @version 2013-11-03
 */
@Controller
@RequestMapping(value = "${adminPath}/book/store")
public class BookStoreController extends BaseController{

    @Autowired
    private BookStoreService bookStoreService;
    @Autowired
    private BookMgrService bookMgrService;
    @Autowired
    private BookPlaceService bookPlaceService;
    @Autowired
    private BookPurchaseDao bookPurchaseDao;
    @Autowired
    private BookPurchaseService bookPurchaseService;

    @ModelAttribute
    public BkBookstore get(@RequestParam(required = false) String id){
        if(StringUtils.isNotBlank(id)){
            return bookStoreService.getById(id);
        }
        else{
            return new BkBookstore();
        }
    }

    @RequiresPermissions("book:store:view")
    @RequestMapping(value = "form")
    public String form(String id, String bkId, String isbn, boolean isEdit, boolean isNew, Model model){

        BkBookinfo bookinfo = null;

        if(StringUtils.isNotEmpty(bkId)){
            if(isNew){
                // 新增一条典藏时
                bookinfo = bookMgrService.get(bkId);
                BkBookstore bookstore = new BkBookstore(bkId);
                bookstore.setClasscode(bookinfo.getClasscode());
                model.addAttribute("bookstore", bookstore);

                List<BkPurchaseBatch> all = bookPurchaseDao.findList(null);
                model.addAttribute("all", all);
            }
            else{
                bookinfo = bookMgrService.get(bkId);
                // 新增后，展示结果
                BkBookstore bkBookstore = bookStoreService.getById(id);
                String store = bkBookstore.getStore();
                if(StringUtils.isNotEmpty(store)){
                    BkPlace bkPlace = bookPlaceService.get(store);
                    if(null != bkPlace){
                        bkBookstore.setStore(bkPlace.getGcdName());
                    }
                }
                model.addAttribute("bookstore", bkBookstore);
            }
        }
        model.addAttribute("bkBookinfo", bookinfo);
        model.addAttribute("isEdit", isEdit);
        model.addAttribute("isNew", isNew);
        model.addAttribute("id", id);
        return "modules/book/bookStoreForm";
    }

    @RequiresPermissions("book:store:view")
    @RequestMapping(value = {"list", ""})
    public String list(BkBookstore bkBookstore, HttpServletRequest request, HttpServletResponse response, Model model){
        String temPlace = bkBookstore.getPlace();
        String classcode = null;
        String place = null;
        if(StringUtils.isNotEmpty(temPlace)){
            String[] places = temPlace.split("/");
            classcode = places[0];
            if(places.length>1){
                place = places[1];
            }else{
                place = "";
            }
        } else {
            classcode = bkBookstore.getClasscode();
        }
        bkBookstore.setClasscode(classcode);
        bkBookstore.setPlace(place);

        Page<BkBookstore> page = bookStoreService.findPage(new Page<>(request, response), bkBookstore);
        model.addAttribute("page", page);
        bkBookstore.setPlace(temPlace);
        return "modules/book/bookStoreList";
    }

    @RequiresPermissions("book:store:save")
    @RequestMapping(value = "saveStore")
    public String saveStore(String id,
                            String bkId,
                            String banid,
                            String autoBanid,
                            String place,
                            String autoPlace,
                            String state,
                            String leftCount,
                            String shelf,
                            Integer batchId,
                            RedirectAttributes redirectAttributes){

        if(!"1".equals(autoBanid) && StringUtils.isEmpty(banid)){
            addMessage(redirectAttributes, "保存典藏数据失败，条形码不能为空！");
            return "redirect:" + adminPath + "/book/store/form?repage&isEdit=true&bkId=" + bkId;
        }
        else{
            String classcode = "";
            if(StringUtils.isNotBlank(place)){
                String[] places = place.split("\\/");
                classcode = places[0].trim();
                if(places.length>=2){
                    place = places[1].trim();
                }
            }

            BkBookstore temkBookstore = new BkBookstore();
            temkBookstore.setId(id);
            temkBookstore.setBkId(bkId);
            //temkBookstore.setPbdId(detail.getPbdId());
            //temkBookstore.setBatch(String.valueOf(batchId));
            temkBookstore.setBanid(banid.trim());
            temkBookstore.setClasscode(classcode);
            //temkBookstore.setBookname(bookname);
            temkBookstore.setStatus(1);
            temkBookstore.setPlace(place);
            temkBookstore.setState("1".equals(state) ? 1 : 0);
            temkBookstore.setTotalCount("1".equals(leftCount) ? 1 : 0);
            temkBookstore.setLeftCount("1".equals(leftCount) ? 1 : 0);
            temkBookstore.setIptTme(new Timestamp(System.currentTimeMillis()));
            temkBookstore.setUserId(UserUtils.getUser().getId());
            temkBookstore.setShelf(new BkShelf(shelf));

            bookStoreService.update(temkBookstore);

            addMessage(redirectAttributes, "修改典藏数据成功！");
            return "redirect:" + adminPath + "/book/store/form?repage&isEdit=true&bkId=" + bkId + "&id=" + id;
        }
    }

    @RequiresPermissions("book:store:cancel")
    @RequestMapping(value = "status")
    @ResponseBody
    public Result cancel(String banid,int status){
        BkBookstore temkBookstore = bookStoreService.get(banid);
        temkBookstore.setStatus(status);

        bookStoreService.update(temkBookstore);
        return new Result(Result.SUCCESS, "状态修改成功！", null);
    }

    @RequiresPermissions("book:store:delete")
    @RequestMapping(value = "delete")
    @ResponseBody
    public Result delete(String storeId){
        int result = bookStoreService.deleteById(storeId);
        if(result > 0){
            return new Result(Result.SUCCESS, "删除典藏数据成功！", null);
        }
        else{
            return new Result(Result.FAILURE, "删除典藏数据失败！", null);
        }
    }

    @RequiresPermissions("book:store:delete")
    @RequestMapping(value = "deleteByStoreId")
    @ResponseBody
    public Result deleteByBanid(String storeId){
        BkBookstore bookstore = bookStoreService.getById(storeId);
        int pbdId = bookstore.getPbdId();

        int result = bookStoreService.deleteById(storeId);

        bookPurchaseDao.reducePurchase(pbdId, 1);

        if(result > 0){
            return new Result(Result.SUCCESS, "删除典藏数据成功！", null);
        }
        else{
            return new Result(Result.FAILURE, "删除典藏数据失败！", null);
        }
    }

    /**
     * 打印标
     * @param batchId batchId
     * @return
     */
    @RequiresPermissions("book:store:print")
    @RequestMapping(value = "print")
    @ResponseBody
    public List<BkBookstore> print(String batchId){
        return bookStoreService.findPrintDetails(batchId);
    }

    /**
     * 打印标
     * @param banid banid
     * @return
     */
    @RequiresPermissions("book:store:print")
    @RequestMapping(value = "printByBanid")
    @ResponseBody
    public BkBookstore printTag(String banid){
        return bookStoreService.findBookStoreByBanid(banid);
    }

    /**
     * 生成条形码
     * @return 条形码
     */
    @RequestMapping(value = "createBan")
    @ResponseBody
    public String createBan(){
        // 设置数据库中的编码初始值
        String maxBarCode = bookStoreService.getMaxBarCode();
        if(StringUtils.isEmpty(maxBarCode)){
            IdGen.formatCount = 0;
            int barCodeLength = maxBarCode.length();
            return IdGen.getMaxCode(barCodeLength);
        }
        else{
            if(maxBarCode.length() >= 4){
                maxBarCode = maxBarCode.substring(4);
                int barCodeLength = maxBarCode.length();
                IdGen.formatCount = Integer.parseInt(maxBarCode);
                return IdGen.getMaxCode(barCodeLength);
            }
            else{
                return String.valueOf(Integer.parseInt(maxBarCode) + 1);
            }
        }
    }

    /**
     * 查询验收的的列表
     *
     * @param bkId
     * @param batch
     * @param model
     * @return
     */
    @RequiresPermissions("book:store:view")
    @RequestMapping(value = "checkList")
    public String checkList(String bkId, String batch, String pbdId, Model model){
        List<BkBookstore> stores = bookStoreService.getCheckList(bkId, batch, pbdId);
        model.addAttribute("stores", stores);

        return "modules/book/pop/checkStoreList";
    }

    /**
     * 查询验收的的列表
     * @param bkId 书籍编号
     * @param batch 批次编号
     * @param pbdId 批次详情编号
     * @return id List
     */
    @RequiresPermissions("book:store:view")
    @RequestMapping(value = "getStoresByBkId")
    @ResponseBody
    public List<BkBookstore> getStoresByBkId(String bkId, String batch, String pbdId){
        return bookStoreService.getCheckList(bkId, batch, pbdId);
    }

    /**
     * 跳转到分配条形码页面
     *
     * @return String
     */
    @RequiresPermissions("book:store:view")
    @RequestMapping(value = "distributBanId")
    public String distributBanId(int amount, int booksAmount,String banids, Model model){
        model.addAttribute("amount", amount * booksAmount);
        model.addAttribute("banids", banids);
        return "modules/book/pop/distributBanId";
    }

    /**
     * 跳转到分配条形码页面
     *
     * @return String
     */
    @RequestMapping(value = "checkRepeatBanIdById")
    @ResponseBody
    public boolean checkRepeatBanIdById(String storeId, String banId){
        return bookStoreService.checkRepeatBanIdById(storeId, banId);
    }

    /**
     * 查询是否有重复的条形码
     *
     * @return String
     */
    @RequestMapping(value = "checkRepeatBanId")
    @ResponseBody
    public Result checkRepeatBanId(String banIds){
        if(StringUtils.isNotEmpty(banIds)){
            // 所有重复的banId
            List<String> banIdList = new ArrayList<>();

            String temBanids = "";

            String[] bans = banIds.split(",");
            Map<String,String> map = new HashMap<>();
            for(String ban : bans){
                if(map.containsKey(ban)){
                    banIdList.add(ban.trim());
                }
                else{
                    temBanids += ",'" + ban.trim() + "'";
                    map.put(ban, ban);
                }
            }
            if(StringUtils.isNotBlank(temBanids) && temBanids.startsWith(",")){
                temBanids = temBanids.substring(1);
            }
            List<String> banIdList1 = bookStoreService.checkRepeatBanId(temBanids);
            banIdList.addAll(banIdList1);
            if(banIdList.isEmpty()){
                return new Result(Result.SUCCESS, "查询重复的条形码", null);
            }
            else{
                return new Result(Result.FAILURE, "查询重复的条形码", banIdList);
            }
        }else{
            return new Result(Result.SUCCESS, "查询重复的条形码", "");
        }
    }

    /**
     * 查询是否有重复的条形码
     *
     * @return String
     */
    @RequestMapping(value = "myLastBanId")
    @ResponseBody
    public Result myLastBanId(){
        User user = UserUtils.getUser();
        String banId = bookStoreService.myLastBanId(user.getLoginName());
        return new Result(Result.SUCCESS, "查询重复的条形码", banId);
    }


    /**
     * 导出馆藏Excel
     * @param bkBookstore
     * @param response
     * @return
     */
    @RequestMapping(value = "export")
    public String exportExcel(BkBookstore bkBookstore, HttpServletResponse response){
        logger.info("BookStoreController.exportExcel() start");
        List<ExportBookstore> list = bookStoreService.findExportList(bkBookstore);
        for(ExportBookstore bookstore : list){
            String othername = bookstore.getOthername();
            if(StringUtils.isNotEmpty(othername)){
                bookstore.setBookname(bookstore.getBookname() + "-" + othername);
            }
        }
        try{
            String fileName = "馆藏信息" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            new ExportExcel("馆藏信息", ExportBookstore.class).setDataList(list).write(response, fileName).dispose();
            return null;
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return "redirect:" + adminPath + "/book/store/?repage";
    }

    /**
     * 总括帐页面
     *
     * @param begin
     * @param end
     * @param model
     * @return
     */
    @RequiresPermissions("book:store:view")
    @RequestMapping("generalLedger")
    public String generalLedger(String begin, String end, String batchNumber, Model model){
        List<GeneralLedger> generalledger = bookStoreService.getGeneralLedger(begin, end, batchNumber);
        if(StringUtils.isEmpty(batchNumber)){
            if(StringUtils.isEmpty(begin)){
                begin = bookStoreService.getMinBarCode();
            }
            if(StringUtils.isEmpty(end)){
                end = bookStoreService.getMaxBarCode();
            }
        }

        List<BkPurchaseBatch> all = bookPurchaseService.findList(null);
        for(BkPurchaseBatch batch : all){
            batch.setRemarks("");
            if(StringUtils.isNotEmpty(batchNumber) && Integer.parseInt(batchNumber) == batch.getBatchId()){
                batch.setRemarks("selected");
            }
        }
        model.addAttribute("all", all);

        model.addAttribute("begin", begin);
        model.addAttribute("end", end);
        model.addAttribute("batchNumber", batchNumber);
        model.addAttribute("generalledger", generalledger);
        return "modules/report/generalLedger";
    }

    /**
     * 导出总括帐Excel
     * @param begin
     * @param end
     * @param response
     * @return
     */
    @RequiresPermissions("book:store:view")
    @RequestMapping(value = "exportGeneralLedger")
    public String exportGeneralLedger(String begin, String end, String batchNumber, HttpServletResponse response){
        List<GeneralLedger> generalledgers = bookStoreService.getGeneralLedger(begin, end, batchNumber);
        int typeAmount = 0;
        int bookAmount = 0;
        Double totalPrice = 0D;
        for(GeneralLedger ledger:generalledgers){
            ledger.setNum(String.valueOf(generalledgers.indexOf(ledger)+1));
            typeAmount += Integer.parseInt(ledger.getCount());
            bookAmount += Integer.parseInt(ledger.getAmount());
            totalPrice += Double.valueOf(ledger.getTotal());
        }
        try{
            GeneralLedger generalLedger = new GeneralLedger();
            generalLedger.setNum("合计：");
            generalLedger.setCount(String.valueOf(typeAmount));
            generalLedger.setAmount(String.valueOf(bookAmount));
            generalLedger.setTotal(String.valueOf(totalPrice));
            generalledgers.add(generalLedger);

            String fileName = "总括账" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            new ExportExcel("总括账", GeneralLedger.class).setDataList(generalledgers).write(response, fileName).dispose();
            return null;
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return "redirect:" + adminPath + "/book/store/generalLedger?repage";
    }

    /**
     * 调换书库弹出框
     * @param storeId
     * @param placeid
     * @param model
     * @return
     */
    @RequiresPermissions("book:store:view")
    @RequestMapping(value = "changestore")
    public String changeStore(String storeId, String placeid,Model model){
        BkPlace bkPlace = bookPlaceService.get(placeid);
        BkBookstore bkStore = bookStoreService.getById(storeId);
        model.addAttribute("bkPlace", bkPlace);
        model.addAttribute("bkStore", bkStore);
        return "modules/book/pop/changeStore";
    }

    /**
     * 保存调拨后的书库信息
     * @param bkStore
     * @param model
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("book:store:save")
    @RequestMapping(value = "changestoresave")
    public String changeStoreSave(BkBookstore bkStore, Model model, RedirectAttributes redirectAttributes){
        BkBookstore saveBkStore = bookStoreService.getById(bkStore.getId());
        saveBkStore.setStore(bkStore.getStore());
        bookStoreService.updateStore(saveBkStore);
        addMessage(redirectAttributes, "图书'" + saveBkStore.getBookname() + "'调整书库成功");
        return "redirect:" + adminPath + "/book/store/changestore?storeId=" + saveBkStore.getId() + "&placeid=" + bkStore.getStore();
    }

    /**
     * 批量修改索书号
     *
     * @param classcode
     * @return
     */
    @RequiresPermissions("book:purchase:view")
    @RequestMapping("goBatchChangePlace")
    public String goBatchChangePlace(String classcode, Model model){
        model.addAttribute("classcode",classcode);
        String[] str = classcode.split("/");
        classcode = str[0];
        String place = null;
        if(str.length >= 2){
            place = str[1];
        }
        place = StringUtils.defaultIfEmpty(place, "");

        List<BkBookstore> stores1;
        if(!place.contains(":") && !place.contains("(") && !place.contains("v")){
            stores1 = bookStoreService.findStoresByClasscode(classcode, place + ":");
            List<BkBookstore> stores2 = bookStoreService.findStoresByClasscode(classcode, place + "(");
            List<BkBookstore> stores3 = bookStoreService.findStoresByClasscode(classcode, place + "v");
            stores1.addAll(stores2);
            stores1.addAll(stores3);
        }
        else{
            stores1 = bookStoreService.findStoresByClasscode(classcode, place);
        }
        model.addAttribute("stores", stores1);
        return "modules/book/pop/batchChangePlace";
    }

    /**
     * 根据 图书编号，批量修改索书号
     *
     * @return String
     */
    @RequestMapping(value = "batchChangePlace")
    public String batchChangePlace(String temClasscode, String[] storeId, String[] classcode, String[] place, RedirectAttributes redirectAttributes){
        List<BkBookstore> list = new ArrayList<>();
        BkBookstore store = null;
        for(int i = 0; i < storeId.length; i++){
            String id = storeId[i];
            String code = classcode[i];
            String tPlace = place[i];
            store = new BkBookstore();
            store.setId(id);
            store.setClasscode(code);
            store.setPlace(tPlace);
            list.add(store);
        }
        bookStoreService.batchChangePlace(list);
        addMessage(redirectAttributes, "批量修改索书号");
        return "redirect:" + adminPath + "/book/store/goBatchChangePlace?classcode=" + temClasscode;
    }

    @RequestMapping(value = "deleteStoreByStoreIds")
    @ResponseBody
    public Result deleteStoreByStoreIds(String storeIds){
        if(StringUtils.isNotEmpty(storeIds) && storeIds.endsWith(",")){
            storeIds = storeIds.substring(0,storeIds.length()-1);
        }
        return bookStoreService.deleteStoreByStoreIds(storeIds);
    }
    /**
     * 根据 图书编号，批量修改索书号
     *
     * @return String
     */
    @RequestMapping(value = "setBookShelfPage")
    public String setBookShelfPage(){
        return "modules/shelf/setBookShelf";
    }

    @RequestMapping(value = "setBookShelf")
    @ResponseBody
    public Result setBookShelf(String shelfId, String setSerNumnber, String setTypeValue){
        return bookStoreService.setBookShelf(shelfId, setSerNumnber, setTypeValue);
    }
}